﻿using DotRas;
using sx_windows.resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sx_windows.utils
{
    public static class Dial
    {
        public static bool PppoeDial(string username, string password)
        {
            try
            {
                //string username = tb_username.Text.Replace("\\r", "\r").Replace("\\n", "\n");
                RasDialer dialer = new RasDialer();
                dialer.EntryName = Const.APP_NAME;
                dialer.PhoneNumber = " ";
                dialer.AllowUseStoredCredentials = true;
                dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
                dialer.Credentials = new System.Net.NetworkCredential(username, password);
                dialer.Timeout = 500;
                RasHandle myras = dialer.Dial();
                while (myras.IsInvalid)
                {
                    return false;
                }
                if (!myras.IsInvalid)
                {
                    RasConnection conn = RasConnection.GetActiveConnectionByHandle(myras);
                    RasIPInfo ipaddr = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP);
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return false;
        }
        public static void CreateConnect()
        {
            RasDialer dialer = new RasDialer();
            string connectName = Const.APP_NAME;
            RasPhoneBook book = new RasPhoneBook();
            try
            {
                book.Open(RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User));
                if (book.Entries.Contains(connectName))
                {
                    book.Entries[connectName].PhoneNumber = " ";
                    book.Entries[connectName].Update();
                }
                else
                {
                    System.Collections.ObjectModel.ReadOnlyCollection<RasDevice> readOnlyCollection = RasDevice.GetDevices();
                    RasDevice device = RasDevice.GetDevices().Where(o => o.DeviceType == RasDeviceType.PPPoE).First();
                    RasEntry entry = RasEntry.CreateBroadbandEntry(connectName, device);
                    entry.PhoneNumber = " ";
                    book.Entries.Add(entry);
                }
            }
            catch (Exception)
            {
                Console.WriteLine("创建PPPoE连接失败");
            }
        }
    }
}
